//index.js
//获取应用实例
var WxSearch = require('../wxSearchView/wxSearchView.js');

const app = getApp()
let wxparse = require("../../wxParse/wxParse.js");
Page({
  data: {
    wordContent: '',
    dkheight: 50,
    br: '\n',
    showIcon: true,
    reg: /[\u4e00-\u9fa5]/g,
    scrollTop: 0,
    articleList: [],
    tips: 0,
    ifverb: 0,
    aList: [],
    goList: [],
    activeNames: 1,
    kk: 1,
    origin: '',
    show: false,
    trans: '',
    info: '',
    infos: '',
    currentPage: 1,
    aPage: 1,
    goPage: 1,
    flag: false,
    hotContent: {},
    dkcontent: "",
    dkcontent2: "",
    vercontent: "",
    touchS: [0, 0],
    touchE: [0, 0],
    hotkeys: [],
    wxSearchData: '',
    autokeys: [],
  },
  touchStart: function(e) {
    // console.log(e.touches[0].pageX)
    let sx = e.touches[0].pageX
    let sy = e.touches[0].pageY
    this.data.touchS = [sx, sy]
  },
  touchMove: function(e) {
    let sx = e.touches[0].pageX;
    let sy = e.touches[0].pageY;
    this.data.touchE = [sx, sy]
  },
  touchEnd: function(e) {
    let _this = this
    let start = this.data.touchS
    let end = this.data.touchE

    console.log(start)
    console.log(end)
    if (start[1] < end[1] - 2) {
      // console.log('下滑')
      _this.setData({
        showIcon: true
      })
    } else if (start[1] > end[1] + 1) {
      // console.log('上滑')
      _this.setData({
        showIcon: false,
      })
      var query = wx.createSelectorQuery();
      query.select('.container').boundingClientRect()
      query.exec((res) => {
        var listHeight = res[0].height; // 获取list高度
        wx.getSystemInfo({
          success: function(res) {
            let realWindowWidth = res.windowWidth
            let realWindowHeight = res.windowHeight
            console.error("container:", listHeight)
            console.error("width:", realWindowWidth)
            console.error("height:", realWindowHeight)

          }

        })
      })
    } else {
      _this.setData({
        showIcon: !_this.data.showIcon
      })
    }
  },
  // 3 转发函数，固定部分，直接拷贝即可
  wxSearchInput: WxSearch.wxSearchInput, // 输入变化时的操作
  setAuto: WxSearch.setAuto, // 自动数组
  wxSearchKeyTap: WxSearch.wxSearchKeyTap, // 点击提示或者关键字、历史记录时的操作
  wxSearchDeleteAll: WxSearch.wxSearchDeleteAll, // 删除所有的历史记录
  wxSearchConfirm: WxSearch.wxSearchConfirm, // 搜索函数
  wxSearchClear: WxSearch.wxSearchClear, // 清空函数
  getHisKeys: WxSearch.getHisKeys,
  wxSearchClear() {
    let _this = this
    console.log('ss')
    let temData = {}
    temData.value = "";
    temData.tipKeys = [];
    // 更新视图
    _this.setData({
      wxSearchData: temData,
      info: ''
    });
  },
  wxSearchConfirm(e) {
    let _this = this
    console.log('ebb', e)
    var key = e.target.dataset.key;
    if (key == 'back') {
      _this.onSearcher()
    } else {
      _this.onSearcher()
      // search(__that.data.wxSearchData.value);
    }
  },
  wxSearchInput(e) {
    let _this = this
    let temData = {}
    let info = e.detail.value;
    temData.hotkeys = _this.data.hotkeys;
    _this.setData({
      info: info,
    })
    wx.request({
      url: `https://www.godic.net/dicts/prefix/${e.detail.value}`,
      method: 'get',
      success: function(res) {
        wx.hideNavigationBarLoading()
        if (res.data.length != 0) {
          temData.tipKeys = res.data.map((item) => {
            return item.value + ' -> ' + item.label
          })
          _this.setData({
            wxSearchData: temData
          })
        } else {
          _this.setData({
            wxSearchData: temData
          })
        }
      },
      fail() {
        _this.setData({
          wxSearchData: temData
        })
      }
    })
    console.log('e', _this.data.wxSearchData)

  },

  // 4 搜索回调函数  
  mySearchFunction: function(value) {
    console.log('value,', value)
    // if (value == '') {
    //   wx.showToast({
    //     title: '请先输入单词',
    //     icon: 'none'
    //   })
    //   return false
    // }
    // wx.navigateTo({
    //   url: `../detail/detail?word=${value}`,
    // })
  },

  // 5 返回回调函数
  myGobackFunction: function() {
    // do your job here
    // 示例：返回
    // wx.redirectTo({
    //   url: '../index/index?searchValue=返回'
    // })
  },
  imgExists: function(e) {
    //默认图片  
    var imgUrl = "2.jpg";
    var img = event.srcElement;
    img.src = imgUrl;
    console.log(img);
    //判断图片大小是否大于0 或者 图片高度与宽度都大于0
    if (img.filesize > 0 || (img.width > 0 && img.height > 0)) {
      e.src = imgUrl;
    } else {
      //默认图片也不存在的时候
    }
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  moveToLocation() {
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },
  strSolver(item) {
    let reg = /[\u4e00-\u9fa5]/g;
    let strs = item.content.replace("\"", "").trim().match(reg);
    console.log("strs", strs)
    if (strs != null && strs.length > 0) {
      let str = strs.join("");
      item.content = str.trim().replace("宋体", "点击查看详情")
    } else {
      item.content = "点击查看详情"
    }
    return item
  },
  getArticle(page, key) {
    let serverUrl = app.serverUrl
    let _this = this
    let url = `${serverUrl}/article/page?moduleId=${key}&current=${page}&size=10`
    // let url = `http://localhost:888/article/page?moduleId=1&current=${page}&size=10`
    wx.request({
      header: app.globalData.header,
      url: url,
      method: "GET",
      success: function(res) {
        console.log("article", res)
        if (res.data.code == 0) {
          wx.hideLoading()
          wx.hideNavigationBarLoading()
          wx.stopPullDownRefresh()
          if (key == 1) {
            let data = res.data.content.records
            let articleList = data;
            let newArticleList = _this.data.articleList;
            let _articleList = newArticleList.concat(articleList)
            for (let item of _articleList) {
              _this.strSolver(item)
            }
            console.log('_articleList', _articleList)
            _this.setData({
              articleList: _articleList,
              currentPage: page,
              totalPage: Math.floor((res.data.content.total / 10)) + 1,
            })
            console.log(_this.data.articleList)
          } else if (key == 2) {
            let data = res.data.content.records
            let aList = data;
            let newArticleList = _this.data.aList;
            let _aList = newArticleList.concat(aList)
            _aList.forEach((item) => {
              console.log("item", item.content)
              let reg = /[\u4e00-\u9fa5]/g;
              let strs = item.content.replace("\"", "").trim().match(reg);
              console.log("strs", strs)
              if (strs != null && strs.length > 0) {
                let str = strs.join("");
                item.content = str.trim().replace("宋体", "【点击查看详情】")
              } else {
                item.content = "【点击查看详情】"
              }
            })
            _this.setData({
              aList: _aList,
              aPage: page,
              total: Math.floor((res.data.content.total / 10)) + 1,
            })
            console.log('aList', res.data.content.records)
          } else if (key == 11) {
            let data = res.data.content.records
            let goList = data;
            let newArticleList = _this.data.goList;
            let _goList = newArticleList.concat(goList)
            _goList.forEach((item) => {
              let reg = /[\u4e00-\u9fa5]/g;
              let strs = item.content.replace("\"", "").trim().match(reg);
              console.log("strs", strs)
              if (strs != null && strs.length > 0) {
                let str = strs.join("");
                item.content = str.trim().replace("宋体", "【点击查看详情】")
              } else {
                item.content = "【点击查看详情】"
              }
            })
            _this.setData({
              goList: _goList,
              goPage: page,
              gototal: Math.floor((res.data.content.total / 10)) + 1,
            })
            console.log('goList', res.data.content.records)
          }
        } else {
          wx.showToast({
            title: '网络出问题了哦..',
            icon: 'none'
          })
        }

      }
    })
  },
  onReachBottom: function(e) {
    console.log("hahhahas")
    let _this = this;
    console.log(_this.data.kk)
    if (_this.data.kk == 1) {
      let currentPage = _this.data.currentPage;
      let totalPage = _this.data.totalPage;
      console.log(currentPage, totalPage)
      //判断当前页数和总页数是否相等，如果相等则无需查询
      if (currentPage === totalPage) {
        wx.showToast({
          title: '已经是全部啦~~~',
          icon: 'none'
        })
        return;
      }
      let page = currentPage + 1;
      if (_this.data.search != undefined && _this.data.search != '') {
        this.onDicSearch(e, -1, page);
      } else {
        this.getArticle(page, 1);
      }
    } else if (_this.data.kk == 2) {
      let currentPage = _this.data.aPage;
      let totalPage = _this.data.total;
      console.log(currentPage, totalPage)
      //判断当前页数和总页数是否相等，如果相等则无需查询
      if (currentPage === totalPage) {
        wx.showToast({
          title: '已经是全部啦~~~',
          icon: 'none'
        })
        return;
      }
      let page = currentPage + 1;
      if (_this.data.search2 != undefined && _this.data.search2 != '') {
        this.onLiuxueSearch(e, -1, page);
      } else {
        this.getArticle(page, 2);
      }
    } else if (_this.data.kk == 3) {
      let currentPage = _this.data.goPage;
      let totalPage = _this.data.gototal;
      console.log(currentPage, totalPage)
      //判断当前页数和总页数是否相等，如果相等则无需查询
      if (currentPage === totalPage) {
        wx.showToast({
          title: '已经是全部啦~~~',
          icon: 'none'
        })
        return;
      }
      let page = currentPage + 1;
      if (_this.data.search3 != undefined && _this.data.search3 != '') {
        this.onLiuxueGoSearch(e, -1, page);
      } else {
        this.getArticle(page, 11);
      }
    }

  },
  onPullDownRefresh: function() {
    let _this = this
    wx.showNavigationBarLoading();
    if (_this.data.kk == 1) {
      this.setData({
        articleList: [],
        currentPage: 1,
        search: '',
        searchValue: ''
      })
      this.getArticle(1, 1);
    } else if (_this.data.kk == 2) {
      this.setData({
        aList: [],
        aPage: 1,
        search2: '',
        searchValue2: ''
      })
      this.getArticle(1, 2);
    } else if (_this.data.kk == 3) {
      this.setData({
        goList: [],
        goPage: 1,
        search3: '',
        searchValue3: ''
      })
      this.getArticle(1, 11);
    }

  },

  toArticle(e) {
    console.log("ee", e)
    let _this = this
    let entity = this.data.articleList[e.target.dataset.arrindex]
    let _id = entity.id
    wx.navigateTo({
      url: `../article/article?id=${_id}&title=${entity.title}`,
    })
  },
  toArticle2(e) {
    let _this = this
    let entity = this.data.aList[e.target.dataset.arrindex]
    let _id = entity.id
    wx.navigateTo({
      url: `../article/article?id=${_id}&title=${entity.title}`,
    })
  },
  toArticle3(e) {
    let _this = this
    let entity = this.data.goList[e.target.dataset.arrindex]
    let _id = entity.id
    entity.title = encodeURIComponent(entity.title.replace("\"", "'").replace("[", "(").replace("]", ")"))
    wx.navigateTo({
      url: `../article/article?id=${_id}&title=${entity.title}`,
    })
  },
  moveToLocation() {
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },
  onLoad: function(param) {
    let _this = this
    wx.checkSession({
      success() {
        console.log('哟西')
        //session_key 未过期，并且在本生命周期一直有效
      },
      fail() {
        _this.wxLogin()
      },
      complete() {
        console.log('hehe', app.globalData.header.Cookie)
        // 获得高度
        console.log('param', param)
        let winPage = _this;
        wx.getSystemInfo({
          success: function(res) {
            let winHeight = res.windowHeight;
            console.log(winHeight);
            winPage.setData({
              dkheight: winHeight - winHeight * 0.05 - 80
            })
          }
        })
        if (param.word != undefined) {
          console.log('ee', param.word)
          let king = {}
          king.value = param.word
          _this.setData({
            wxSearchData: king,
            info: param.word,
            value: param.word
          })
          _this.onSearcher()
        } else {
          _this.setData({
            activeName: 1
          })
        }
        _this.getArticle(1, 1)
        _this.getArticle(1, 2)
        _this.getArticle(1, 11)
      }
    })

  },
  onClose() {
    this.setData({
      show: false
    });
    wx.showToast({
      title: '加载中请耐心等待..',
      icon: 'none'
    })
  },
  onSearcher(e) {
    let _this = this
    if (this.data.info == undefined || this.data.info == '') {
      wx.showToast({
        title: '请先输入单词',
        icon: 'none'
      })
      return false
    }
    let temData = {}
    temData.tipKeys = [];
    // 更新视图
    _this.setData({
      origin: '',
      wxSearchData: temData,
      trans: '',
      show: true
    })

    let serverUrl = app.serverUrl
    let url = `${serverUrl}/dic/getv/${_this.data.info}`
    // let url = `http://localhost:888/dic/getv/${this.data.info}`
    console.log('ulrr', url)
    wx.request({
      header: app.globalData.header,
      url: url,
      method: "GET",
      success: function(res) {
        console.log('ff', res)
        let core = res.data.content.core
        console.error("core,",core)
        if (res.data.code == 0) {
          _this.setData({
            wordContent: res.data.content,
            wxSearchData: {},
            infos: 1,
            show: false
          })
          if (res.data.content.ver != null && res.data.content.ver != undefined && res.data.content.ver != "") {
            _this.setData({
              ifverb: 1
            })
          }
          if (core.indexOf("<!--&-->") != -1) {
            let cores = core.split("<!--&--><br>")
            let origin = cores[0]
            let trans = cores[1]
            _this.setData({
              origin: origin,
              trans: trans,
            })
          }

          // name.match('/[\u4e00-\u9fa5]/g').join("");
          // name = names.join("");
          wxparse.wxParse('dkcontent', 'html', core.replace('img src', 'img style="width:100%;" src'), _this, 15);
          wxparse.wxParse('dkcontent2', 'html', res.data.content.exemplify, _this, 15);
          try {
            wxparse.wxParse('vercontent', 'html', res.data.content.ver, _this, 15);
          } catch (e) {
            console.log('缺少HTML标签')
            return
          }
        } else {
          if (_this.data.tips >= 3) {
            wx.showToast({
              title: '您所在的地区可能无法使用',
              icon: 'none',
              duration: 3000
            })
            return
          }
          _this.wxLogin()
          wx.showLoading({
            title: '正在重连...',
          })
          _this.setData({
            tips: _this.data.tips + 1
          })
          setTimeout(_this.onSearcher, 800)
          // setTimeout(wx.navigateBack, 800)
        }

      }
    })
  },
  onDicSearch(e, key, page, kk) {
    let _this = this
    console.log(key, page)
    let title = _this.data.search
    if (title == undefined || title == '') {
      wx.showToast({
        title: '请输入关键词',
        icon: 'none'
      })
      return false
    }
    page = page == undefined ? 1 : page
    let serverUrl = app.serverUrl
    if (key != -1) {
      _this.setData({
        articleList: [],
      })
    }

    let url = `${serverUrl}/article/page?title=${title}&current=${page}&size=10&moduleId=1`
    // let url = `http://localhost:888/article/page?title=${this.data.search}&current=${page}&size=10`
    wx.request({
      header: app.globalData.header,
      url: url,
      method: "GET",
      success: function(res) {
        console.log("articleee", res)
        if (res.data.code == 0) {
          wx.hideLoading()
          wx.hideNavigationBarLoading()
          let data = res.data.content.records
          // _this.setData({
          //   articleList: []
          // })
          let articleList = data;
          let newArticleList = _this.data.articleList;

          let _articleList = newArticleList.concat(articleList)
          for (let item of _articleList) {
            item.content = item.content.replace('<div>', '').replace('<p>', '')
          }
          console.log('_articleList', _articleList)
          _this.setData({
            articleList: _articleList,
            currentPage: page,
            totalPage: Math.floor((res.data.content.total / 10)) + 1,
          })
          console.log(_this.data.articleList)
        } else {
          wx.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          })
          _this.wxLogin()

        }

      }
    })
  },
  wxLogin() {
    let _this = this
    wx.login({
      success(res) {
        _this.setData({
          id: res.code
        })
        console.error('res.code', res.code)
        wx.getSetting({
          success: function(ret) {

            wx.getUserInfo({
              lang: "zh_CN",
              withCredentials: true,
              success: function(info) {
                console.log('res', info)
                let s = JSON.parse(info.rawData)
                console.error('s.avatarUrl', s.avatarUrl, s.nickName)
                console.error(s.avatarUrl == '')
                if (s.nickName != null && s.avatarUrl != null) {
                  let avatar = s.avatarUrl
                  avatar = s.avatarUrl == '' ? 'http://zzuisa.cn/unlogin.png' : s.avatarUrl
                  wx.request({
                    url: app.serverUrl + `/user/member/wxlogin`,
                    method: 'post',
                    data: {
                      code: res.code,
                      name: s.nickName,
                      headerImg: avatar,
                      gender: s.gender,
                      province: s.province,
                      city: s.city
                    },
                    success: function(reso) {
                      console.log('resooo', reso)
                      if (reso.data.code == 0) {
                        wx.hideLoading()
                        _this.setData({
                          userInfo: reso.data.content
                        })
                        app.setGlobalUserInfo(reso.data.content)
                        app.globalData.header.Cookie = reso.header["Set-Cookie"];
                        wx.hideLoading()
                        if (_this.data.page != undefined) {
                          let page = _this.data.page
                          wx.navigateTo({
                            url: decodeURIComponent(page.replace('article@', 'article?').replace('video@', 'video?'))
                          })
                        }
                      }

                    }
                  })
                }

              }
            })
          }
        })
      }
    })
  },
  onLiuxueSearch(e, key, page) {
    console.log(key, page)
    let _this = this

    let title = _this.data.search2

    if (title == undefined || title == '') {
      wx.showToast({
        title: '请输入关键词',
        icon: 'none'
      })
      return false
    }
    page = page == undefined ? 1 : page
    let serverUrl = app.serverUrl
    if (key != -1) {
      _this.setData({
        aList: [],
      })
    }
    let url = `${serverUrl}/article/page?title=${title}&current=${page}&size=10&moduleId=2`
    // let url = `http://localhost:888/article/page?title=${this.data.search}&current=${page}&size=10`
    wx.request({
      header: app.globalData.header,
      url: url,
      method: "GET",
      success: function(res) {
        console.log("articleee", res)
        if (res.data.code == 0) {
          wx.hideLoading()
          wx.hideNavigationBarLoading()
          let data = res.data.content.records
          // _this.setData({
          //   articleList: []
          // })
          let aList = data;
          let newArticleList = _this.data.aList;
          _this.setData({
            aList: newArticleList.concat(aList),
            aPage: page,
            total: Math.floor((res.data.content.total / 10)) + 1,
          })
        } else {
          wx.showToast({
            title: '网络出问题了哦..',
            icon: 'none'
          })
        }

      }
    })
  },
  onLiuxueGoSearch(e, key, page) {
    console.log(key, page)
    let _this = this

    let title = _this.data.search3

    if (title == undefined || title == '') {
      wx.showToast({
        title: '请输入关键词',
        icon: 'none'
      })
      return false
    }
    page = page == undefined ? 1 : page
    let serverUrl = app.serverUrl
    if (key != -1) {
      _this.setData({
        goList: [],
      })
    }
    let url = `${serverUrl}/article/page?title=${title}&current=${page}&size=10&moduleId=11`
    // let url = `http://localhost:888/article/page?title=${this.data.search}&current=${page}&size=10`
    wx.request({
      header: app.globalData.header,
      url: url,
      method: "GET",
      success: function(res) {
        console.log("articleeesss", res)
        if (res.data.code == 0) {
          wx.hideLoading()
          wx.hideNavigationBarLoading()
          let data = res.data.content.records
          // _this.setData({
          //   articleList: []
          // })
          let goList = data;
          let newArticleList = _this.data.goList;
          _this.setData({
            goList: newArticleList.concat(goList),
            goPage: page,
            gototal: Math.floor((res.data.content.total / 10)) + 1,
          })
        } else {
          wx.showToast({
            title: '网络出问题了哦..',
            icon: 'none'
          })
        }

      }
    })
  },

  onChange(e) {
    this.setData({
      info: e.detail
    })
  },
  onDicChange(e) {
    this.setData({
      search: e.detail
    })
  },
  onLiuxueChange(e) {
    this.setData({
      search2: e.detail
    })
  },
  onLiuxueGoChange(e) {
    this.setData({
      search3: e.detail
    })
  },
  change(event) {
    this.setData({
      activeNames: event.detail,
      kk: event.detail.index
    });
    if (event.detail.index == 0) {

    } else if (event.detail.index == 2) {
      if (wx.getStorageSync("read") != 1) {
        wx.showModal({
          title: '提示',
          content: '【德国留学】模块新增最新信息【NEW】',
          success(res) {
            if (res.confirm) {
              wx.setStorageSync("read", 1)
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    } else if (event.detail.index == 4) {
      if (wx.getStorageSync("read2") != 1) {
        wx.showModal({
          title: '正在开发中...',
          content: `目前小程序为满足个人自学德语所需，主要是为查词，现在也是发布出来，希望能帮到大家。\n开发始于2019-06-03，会在闲暇之余处理反馈~`,
          success(res) {
            if (res.confirm) {
              wx.setStorageSync("read2", 1)
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }
    console.log('ree', event)
  },
  onShareAppMessage() {},
  getHot(word) {
    let serverUrl = app.serverUrl
    let _this = this
    let url = `${serverUrl}/dic/hot`
    // let url = `http://localhost:888/dic/hot`
    wx.request({
      header: app.globalData.header,
      url: url,
      method: "GET",
      success: function(res) {
        if (res.data.code == 0) {
          _this.setData({
            hotContent: res.data.content
          })
          console.log('htot', _this.data.hotContent)
          // wxparse.wxParse('dkcontent', 'html', res.data.content, this, 5);

        }

      }
    })
  },
  previewImage: function(e) {
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, // 当前显示图片的http链接 
      urls: ['/Images/2.png'] // 需要预览的图片http链接列表 
    })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})